package com.rcloud.stock.ui.detail;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.rcloud.stock.R;
import com.rcloud.stock.adapter.DetailGgRecyclerAdapter;
import com.rcloud.stock.adapter.DetailZxRecyclerAdapter;
import com.rcloud.stock.adapter.ViewRecyclerAdapter;
import com.rcloud.stock.bean.Stock;
import com.rcloud.stock.databinding.FragmentDetailBinding;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

public class DetailFragment extends Fragment {

    private Stock stock;
    private FragmentDetailBinding binding;
    private ArrayList<String> titles;
    private DetailZxRecyclerAdapter zxRecyclerAdapter;
    private DetailGgRecyclerAdapter ggRecyclerAdapter;
    private DetailViewModel detailViewModel;
    private ViewPager2 viewPager2;
    private TabLayout tabLayout2;
    private ImageView showImageView,hideImageView;
    private BottomSheetBehavior bottomSheetBehavior;
    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        detailViewModel = new ViewModelProvider(requireActivity()).get(DetailViewModel.class);
        //获取参数
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_detail, container, false);
        stock = (Stock) requireArguments().getSerializable("stock");
        binding.setLifecycleOwner(this);
        initView();
        initListener();
        //请求资讯和公告数据
        detailViewModel.fetchZx(stock.getCode());
        detailViewModel.fetchGg(stock.getCode());
        return binding.getRoot();
    }

    private void initListener() {
        //等待数据获取进行渲染
        detailViewModel.zxLive.observe(getViewLifecycleOwner(),zxes -> {
            //获取所有title数据
            if (zxes!=null){
                zxRecyclerAdapter.submitList(zxes);
            }
        });
        detailViewModel.ggLive.observe(getViewLifecycleOwner(),ggs -> {
            //获取所有title数据
            if (ggs!=null){
                ggRecyclerAdapter.submitList(ggs);
            }
        });
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String[] urls = {"fenshi", "day", "ma5", "ma10", "ma20", "ma30"};
                binding.klineWebView.loadUrl("file:///android_asset/" + urls[tab.getPosition()] + ".html");
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}
            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });

        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                Log.d("amy",position+"");
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });

        binding.backImageView.setOnClickListener(v -> {
            NavController controller = Navigation.findNavController(v);
            controller.navigateUp();
        });

        showImageView.setOnClickListener(v -> {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        });

        hideImageView.setOnClickListener(v -> {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        });
    }

    @SuppressLint({"SetJavaScriptEnabled", "SetTextI18n"})
    private void initView() {
        //填充顶部数据
        binding.nameTv.setText(stock.getName());
        binding.codeTv.setText(stock.getCode());
        binding.lpTv.setText(String.valueOf(stock.getLp()));
        binding.zdeTv.setText(String.valueOf(stock.getZde()));
        binding.zdfTv.setText(stock.getZdf() + "%");
        if (!stock.getCjl().equals("-")) {
            long cjl = Long.parseLong(stock.getCjl());
            long divide = 100000000;
            String unit = "亿";
            if (cjl / divide == 0) {
                divide = 10000;
                unit = "万";
            }
            binding.cjlTv.setText(Double.valueOf(String.format("%.2f", cjl * 1.0 / divide)) + unit);
        } else binding.cjlTv.setText("-");
        if (!stock.getCje().equals("-")) {
            long cje = Long.parseLong(stock.getCje());
            long divide = 100000000;
            String unit = "亿";
            if (cje / divide == 0) {
                divide = 10000;
                unit = "万";
            }
            binding.cjeTv.setText(Double.valueOf(String.format("%.2f", cje * 1.0 / divide)) + unit);
        } else binding.cjeTv.setText("-");
        binding.highTv.setText(String.valueOf(stock.getHigh()));
        binding.lowTv.setText(String.valueOf(stock.getLow()));
        binding.toTv.setText(String.valueOf(stock.getTo()));
        binding.zsTv.setText(String.valueOf(stock.getZs()));

        //绘制K线图
        binding.klineWebView.getSettings().setJavaScriptEnabled(true);
        binding.klineWebView.loadUrl("file:///android_asset/fenshi.html");
        binding.klineWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        //初始化底部抽屉
        bottomSheetBehavior = BottomSheetBehavior.from(binding.bottomLayout);
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        viewPager2 = binding.bottomLayout.findViewById(R.id.viewPager2);
        tabLayout2 = binding.bottomLayout.findViewById(R.id.tabLayout2);
        showImageView = binding.bottomLayout.findViewById(R.id.showImageView);
        hideImageView = binding.bottomLayout.findViewById(R.id.hideImageView);
        //设置资讯和公告
        initPager();
    }

    public void initPager(){
        titles = new ArrayList<>();
        titles.add("资讯");
        titles.add("公告");
        zxRecyclerAdapter = new DetailZxRecyclerAdapter();
        ggRecyclerAdapter = new DetailGgRecyclerAdapter();
        viewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        ViewRecyclerAdapter pagerAdapter = new ViewRecyclerAdapter(requireActivity(),zxRecyclerAdapter,ggRecyclerAdapter);
        viewPager2.setAdapter(pagerAdapter);
        new TabLayoutMediator(tabLayout2, viewPager2, (TabLayoutMediator.TabConfigurationStrategy) (tab, position) -> tab.setText(titles.get(position))).attach();
    }
}